// 模拟包裹数据
const packages = [
  { trackingNumber: 'SF1234567890', sourceStation: 'station1', targetStation: 'stationA', status: '已签收' },
  { trackingNumber: 'YT0987654321', sourceStation: 'station2', targetStation: 'stationB', status: '运输中' },
  { trackingNumber: 'JD1357924680', sourceStation: 'station1', targetStation: 'stationB', status: '已揽收' },
  { trackingNumber: 'ZT2468013579', sourceStation: 'station2', targetStation: 'stationA', status: '派送中' },
  { trackingNumber: 'YD1122334455', sourceStation: 'station1', targetStation: 'stationA', status: '退货中' },
  { trackingNumber: 'EMS5566778899', sourceStation: 'station2', targetStation: 'stationB', status: '已到达' },
  { trackingNumber: 'ST9988776655', sourceStation: 'station1', targetStation: 'stationB', status: '已发出' },
  { trackingNumber: 'TT1234567890', sourceStation: 'station2', targetStation: 'stationA', status: '运输中' },
  { trackingNumber: 'QF0987654321', sourceStation: 'station1', targetStation: 'stationA', status: '派送中' },
  { trackingNumber: 'DB1357924680', sourceStation: 'station2', targetStation: 'stationB', status: '已签收' },
  { trackingNumber: 'ZD2468013579', sourceStation: 'station1', targetStation: 'stationB', status: '已揽收' },
  { trackingNumber: 'HT1122334455', sourceStation: 'station2', targetStation: 'stationA', status: '运输中' },
  { trackingNumber: 'YZ5566778899', sourceStation: 'station1', targetStation: 'stationA', status: '已到达' },
  { trackingNumber: 'FA9988776655', sourceStation: 'station2', targetStation: 'stationB', status: '退货中' },
  { trackingNumber: 'KL1234567890', sourceStation: 'station1', targetStation: 'stationB', status: '已发出' },
  { trackingNumber: 'AX0987654321', sourceStation: 'station2', targetStation: 'stationA', status: '派送中' },
  { trackingNumber: 'BV1357924680', sourceStation: 'station1', targetStation: 'stationA', status: '已签收' },
  { trackingNumber: 'CJ2468013579', sourceStation: 'station2', targetStation: 'stationB', status: '运输中' },
  { trackingNumber: 'DK1122334455', sourceStation: 'station1', targetStation: 'stationB', status: '已揽收' },
  { trackingNumber: 'EL5566778899', sourceStation: 'station2', targetStation: 'stationA', status: '已到达' },
  { trackingNumber: 'FM9988776655', sourceStation: 'station1', targetStation: 'stationA', status: '已发出' },
  { trackingNumber: 'GN1234567890', sourceStation: 'station2', targetStation: 'stationB', status: '派送中' },
  { trackingNumber: 'HP0987654321', sourceStation: 'station1', targetStation: 'stationB', status: '已签收' },
  { trackingNumber: 'IQ1357924680', sourceStation: 'station2', targetStation: 'stationA', status: '运输中' },
  { trackingNumber: 'JR2468013579', sourceStation: 'station1', targetStation: 'stationA', status: '退货中' }
];

// 全局变量
let currentPage = 1;
const itemsPerPage = 10;
let filteredPackages = [...packages];

// DOM 元素
const trackingNumberSearch = document.getElementById('trackingNumberSearch');
const sourceStationSelect = document.getElementById('sourceStation');
const targetStationSelect = document.getElementById('targetStation');
const searchBtn = document.getElementById('searchBtn');
const packageTableBody = document.getElementById('packageTableBody');
const pageNumbersContainer = document.getElementById('pageNumbers');
const prevPageBtn = document.getElementById('prevPage');
const nextPageBtn = document.getElementById('nextPage');
const filterCheckboxes = document.querySelectorAll('.filter-options input[type="checkbox"]');
const tableHeaders = document.querySelectorAll('#packageTable th');

// 初始化
function init() {
  renderTable();
  renderPagination();
  addEventListeners();
}

// 渲染表格
function renderTable() {
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const paginatedPackages = filteredPackages.slice(startIndex, endIndex);

  packageTableBody.innerHTML = '';

  if (paginatedPackages.length === 0) {
    const row = document.createElement('tr');
    row.innerHTML = `<td colspan="5" style="text-align: center; padding: 20px;">没有找到匹配的包裹</td>`;
    packageTableBody.appendChild(row);
    return;
  }

  paginatedPackages.forEach(pkg => {
    const row = document.createElement('tr');
    row.innerHTML = `
      <td data-column="trackingNumber">${pkg.trackingNumber}</td>
      <td data-column="sourceStation">${pkg.sourceStation === 'station1' ? '来源站1' : '来源站2'}</td>
      <td data-column="targetStation">${pkg.targetStation === 'stationA' ? '目标站A' : '目标站B'}</td>
      <td data-column="status">${pkg.status}${pkg.status === '退货中' ? ' <span style="color: red;">(returning)</span>' : ''}</td>
      <td data-column="actions"><button class="detail-btn" onclick="window.location.href='Package Detail Page.html?trackingNumber=${pkg.trackingNumber}'">详情</button></td>
    `;
    packageTableBody.appendChild(row);
  });

  // 更新列可见性
  updateColumnVisibility();
}

// 渲染分页
function renderPagination() {
  const totalPages = Math.ceil(filteredPackages.length / itemsPerPage);
  pageNumbersContainer.innerHTML = '';

  // 添加页码
  for (let i = 1; i <= totalPages; i++) {
    const pageNumber = document.createElement('div');
    pageNumber.className = `page-number ${i === currentPage ? 'active' : ''}`;
    pageNumber.textContent = i;
    pageNumber.addEventListener('click', () => {
      currentPage = i;
      renderTable();
      renderPagination();
    });
    pageNumbersContainer.appendChild(pageNumber);
  }

  // 更新按钮状态
  prevPageBtn.disabled = currentPage === 1;
  nextPageBtn.disabled = currentPage === totalPages;
}

// 添加事件监听器
function addEventListeners() {
  // 搜索按钮点击事件
  searchBtn.addEventListener('click', performSearch);

  // 回车键搜索
  trackingNumberSearch.addEventListener('keyup', (e) => {
    if (e.key === 'Enter') performSearch();
  });

  // 下拉框变化事件
  sourceStationSelect.addEventListener('change', performSearch);
  targetStationSelect.addEventListener('change', performSearch);

  // 分页按钮事件
  prevPageBtn.addEventListener('click', () => {
    if (currentPage > 1) {
      currentPage--;
      renderTable();
      renderPagination();
    }
  });

  nextPageBtn.addEventListener('click', () => {
    const totalPages = Math.ceil(filteredPackages.length / itemsPerPage);
    if (currentPage < totalPages) {
      currentPage++;
      renderTable();
      renderPagination();
    }
  });

  // 过滤选项变化事件
  filterCheckboxes.forEach(checkbox => {
    checkbox.addEventListener('change', updateColumnVisibility);
  });
}

// 执行搜索
function performSearch() {
  const trackingNumber = trackingNumberSearch.value.toLowerCase();
  const sourceStation = sourceStationSelect.value;
  const targetStation = targetStationSelect.value;

  filteredPackages = packages.filter(pkg => {
    const matchesTrackingNumber = pkg.trackingNumber.toLowerCase().includes(trackingNumber);
    const matchesSourceStation = !sourceStation || pkg.sourceStation === sourceStation;
    const matchesTargetStation = !targetStation || pkg.targetStation === targetStation;

    return matchesTrackingNumber && matchesSourceStation && matchesTargetStation;
  });

  currentPage = 1; // 重置到第一页
  renderTable();
  renderPagination();
}

// 更新列可见性
function updateColumnVisibility() {
  filterCheckboxes.forEach(checkbox => {
    const column = checkbox.getAttribute('data-column');
    const isChecked = checkbox.checked;

    // 更新表头
    tableHeaders.forEach(header => {
      if (header.getAttribute('data-column') === column) {
        header.style.display = isChecked ? '' : 'none';
      }
    });

    // 更新表格内容
    const tableCells = document.querySelectorAll(`td[data-column="${column}"]`);
    tableCells.forEach(cell => {
      cell.style.display = isChecked ? '' : 'none';
    });
  });
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', init);